package cn.youth996.nav.service.impl;

import cn.youth996.nav.service.NominatimService;
import cn.youth996.nav.util.CoordinateTransformUtils;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.List;
import java.util.Map;

/**
 * Nominatim 查询实现类
 *
 * @author Zhan Xinjian
 * @date 2025/5/14
 */
@Slf4j
@Service
public class NominatimServiceImpl implements NominatimService {
    @Autowired
    private RestTemplate restTemplate;
    private static final String NOMINATIM_URL = "http://dev10.youth996.cn:8060/search.php";

    @Override
    public List<Map<String, Object>> queryLocation(String query) throws IOException, InterruptedException {
        HttpClient client = HttpClient.newHttpClient();
        String url = NOMINATIM_URL+"?q=" + query + "&format=json";
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .header("User-Agent", "Mozilla/5.0")
                .header("Accept", "application/json")
                .GET()
                .build();
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

        // 解析返回的 JSON 数据
        ObjectMapper objectMapper = new ObjectMapper();
        List<Map<String, Object>> locations = objectMapper.readValue(response.body(), new TypeReference<List<Map<String, Object>>>() {});

        // 对每个地点的经纬度进行转换
        for (Map<String, Object> location : locations) {
            String latStr = (String) location.get("lat");
            String lonStr = (String) location.get("lon");

            // 转换为 GCJ-02 坐标
            double lat = Double.parseDouble(latStr);
            double lon = Double.parseDouble(lonStr);
            double[] gcj02 = CoordinateTransformUtils.transform(lat, lon);

            // 更新坐标
            location.put("gcj02_lat", gcj02[0]);
            location.put("gcj02_lon", gcj02[1]);
        }

        return locations;

    }
}
